const Service = require('egg').Service
const mkdirp = require('mkdirp');
const sd = require('silly-datetime');
const path = require("path");
const fs = require('fs')

// 工具服务
class ToolSerive extends Service {

  /**
   * 获取文件上传目录
   * @param {*} filename
   */
  async getUploadFile(filename) {
    // 1.获取当前日期
    let day = sd.format(new Date(), 'YYYYMMDD');
    // 2.创建图片保存的路径
    let dir = path.join(this.config.uploadDir, day);
    await mkdirp(dir); // 不存在就创建目录
    let date = Date.now(); // 毫秒数
    let suffix = path.extname(filename)
    let _filename = filename.split(suffix)[0]
    // 返回图片保存的路径
    let uploadDir = path.join(dir, _filename +'-'+ date + suffix);
    return {
      filename: date + suffix,
      uploadDir,
      saveDir: this.config.imgDomain + uploadDir.slice(3).replace(/\\/g, '/')
    }
  }

  /**
   * 删除磁盘文件
   * @param {*} url
   */
  deleteDiskFile(url) {
    const filePath = url.split(this.config.imgDomain)[1]
    try {
      data = fs.unlinkSync(path.join(process.cwd(), '/app' + filePath))
    } catch (error) {
      //throw error(error)
    }
  }

  /**
   * 构建树形结构数据
   * @param {*} data 
   * @param {*} parentId 父级ID
   * @param {*} self   自身ID 
   */
  buildTree(data, parentId, self) {
    let parents = data.filter(value => value[parentId] == undefined || value[parentId] == null || value[parentId] === '')
    let children = data.filter(value => value[parentId] != undefined && value[parentId] !== null && value[parentId] !== '')
    let translator = (parents, children) => {
      parents.forEach((parent) => {
        children.forEach((current, index) => {
          if (current[parentId] === parent[self]) {
            let temp = JSON.parse(JSON.stringify(children))
            temp.splice(index, 1)
            translator([current], temp)
            typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]
          }
        })
      })
    }
    translator(parents, children)
    return parents
  }

  /**
   * 将数据转化成JSON格式
   * @param {*} data
   */
  toJson(data) {
    return JSON.parse(JSON.stringify(data))
  }
}

module.exports = ToolSerive